<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js深拷贝 递归</title>
</head>

<body>
    <h2>js深拷贝 递归</h2>
    <script>
        const obj1 = {
            name: '222',
            address: {
                city: 'beijing'
            },
            arr: ['a', 'b']
        }
        const obj2 = deepClone(obj1)
            // const obj2 = JSON.parse(JSON.stringify(obj1))
        obj2.name = '5555';
        obj2.arr[1] = 3
        console.log(obj1.name, obj2.name, obj2.arr, obj1.arr)

        function deepClone(obj = {}) {
            if (typeof obj !== 'object' || obj == null) return obj
            var result
            if (obj instanceof Array) {
                result = []
            } else {
                result = {}
            }
            for (var k in obj) {
                if (obj.hasOwnProperty(k)) {
                    // 递归
                    result[k] = deepClone(obj[k])
                }
            }
            return result
        }
    </script>
</body>

</html>